package com.iceking.dao;

import com.iceking.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

/**
 * Created by I on 2015/8/16.
 */
@Repository
public class UserDaoImplHiber implements UserDao {

    @Autowired
    private SessionFactory sessionFactory;

//    private Session session = sessionFactory.openSession();

    @Transactional
    public void add(User user) {
        Session session = sessionFactory.getCurrentSession();
        session.save(user);
    }

    @Transactional
    public void update(User user) {
        Session session = sessionFactory.getCurrentSession();
        session.update(user);
    }

    @Transactional
    public void delete(long id) {
        Session session = sessionFactory.getCurrentSession();
        User user = (User) session.load(User.class, id);
        System.out.println("User in Hiber : " + user);
        session.delete(user);
    }

    @Transactional
    public List<User> list() {
        Session session = sessionFactory.getCurrentSession();
        List<User> users = session.createQuery("from User").list();
        return users;
    }

    @Transactional
    public User getUserById(long id) {
        Session session = sessionFactory.getCurrentSession();
//        return (User) session.get(User.class, id);
        return (User) session.load(User.class, id); //会报错因为代理对象没法初始化
    }
}
